import { BuilderHTMLElement, FarrisDesignBaseNestedComponent } from '@farris/designer-element';
import { HtmlTemplateSchema } from '../schema/schema';
import { HTMLProp } from '../property/property-config';
import { ElementPropertyConfig } from '@farris/ide-property-panel';
import { FormPropertyChangeObject } from '../../../../entity/property-change-entity';
import { HtmlTemplateDragDropManager } from '../drag-drop/dragAndDrapManager';
import { DesignerEnvType, FormBasicService } from '@farris/designer-services';
import { NoCodeHTMLProp } from '../property/nocode-property-config';

export default class HtmlTemplateComponent extends FarrisDesignBaseNestedComponent {


    private dragManager: HtmlTemplateDragDropManager;

    constructor(component: any, options: any) {
        super(component, options);

        this.dragManager = new HtmlTemplateDragDropManager(this);
        this.dragManager.checkIsInFixedContextRules();
    }


    getDefaultSchema(): any {
        return HtmlTemplateSchema;
    }

    getStyles(): string {
        const styles = 'display: inherit;flex: 1;flex-direction: inherit;flex-wrap: inherit;justify-content: inherit;align-items: inherit;width: 100%;padding:0;border:0;';

        return styles;
    }


    render(): any {
        const shownHtml = this.parseI18nResource(this.component.html);
        return super.render(this.renderTemplate('HtmlTemplate', {
            component: this.component,
            shownHtml
        }));


    }

    /**
     * 组装属性面板配置数据
     */
    getPropertyConfig(): ElementPropertyConfig[] {
        const serviceHost = this.options.designerHost;

        const formBasicService = serviceHost.getService('FormBasicService') as FormBasicService;

        if (formBasicService && formBasicService.envType === DesignerEnvType.noCode) {
            const prop: NoCodeHTMLProp = new NoCodeHTMLProp(serviceHost, this.viewModelId, this.componentId);
            const propertyConfig: ElementPropertyConfig[] = prop.getPropConfig(this.component);
            return propertyConfig;
        } else {
            const prop: HTMLProp = new HTMLProp(serviceHost, this.viewModelId, this.componentId);
            const propertyConfig: ElementPropertyConfig[] = prop.getPropConfig(this.component);
            return propertyConfig;
        }

    }


    /**
     * 属性变更后事件：默认监听样式类属性变更，并触发模板重绘
     * @param changeObject 变更集
     * @param propertyIDs 需要额外监听的属性ID列表
     */
    onPropertyChanged(changeObject: FormPropertyChangeObject): void {

        if (changeObject.propertyID === 'html') {
            this.triggerRedraw();
        }

    }


    checkCanMoveComponent(): boolean {
        const canMove: boolean = super.checkCanMoveComponent();
        if (!canMove) {
            return false;
        }

        return this.dragManager.canMove;
    }

    checkCanDeleteComponent(): boolean {
        const canDelete: boolean = super.checkCanDeleteComponent();
        if (!canDelete) {
            return false;
        }
        return this.dragManager.canDelete;
    }

    canAccepts(sourceElement: BuilderHTMLElement, targetElement?: BuilderHTMLElement): boolean {
        return false;
    }

    /**
     * 为了展示效果，截取国际化配置项的默认值
     * @param originalContent
     * <button class="btn btn-secondary f-btn-ml" id="prdocitem-button-remove" >{{'itemDelete' | lang:lang:'删除'}}</button>
     */
    private parseI18nResource(originalContent: string): string {
        if (!originalContent) {
            return '';
        }
        // 1、截取{{}} 之间的内容
        const reg = /\{\{[^\}]+\}\}/gi;
        const matchedI18nResources = originalContent.match(reg);
        if (!matchedI18nResources || matchedI18nResources.length === 0) {
            return originalContent;
        }
        matchedI18nResources.forEach(orignalResource => {
            // 2、先移除空格，再判断当前表达式是否包含国际化配置
            const hasI18nLang = orignalResource.replace(/\s+/g, '').includes('lang:lang:');
            if (!hasI18nLang) {
                return;
            }
            const langIndex = orignalResource.lastIndexOf('lang');
            if (langIndex <= 0) {
                return;
            }

            const langStr = orignalResource.slice(langIndex);

            // 3、匹配单引号或双引号之间的文本
            let defaultValueReg = /\'([^\']*)\'/gi;
            if (langStr.indexOf('\"') > 0) {
                defaultValueReg = /\"([^\"]*)\"/gi;
            }
            const matchedDefaultValues = langStr.match(defaultValueReg);
            if (matchedDefaultValues && matchedDefaultValues.length) {
                const defaultValue = matchedDefaultValues[0].slice(1, matchedDefaultValues[0].length - 1);
                if (defaultValue) {
                    // 4、用默认值替换国际化配置表达式
                    originalContent = originalContent.replace(orignalResource, defaultValue);
                }
            }


        });
        return originalContent;
    }

}

